package com.tianji.learning.mq;

import com.tianji.api.dto.trade.OrderBasicDTO;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.domain.query.PageQuery;
import com.tianji.common.utils.CollUtils;
import com.tianji.learning.domain.po.LearningLesson;
import com.tianji.learning.domain.po.LearningRecord;
import com.tianji.learning.mapper.LearningRecordMapper;
import com.tianji.learning.redis.RedisCacheTemplate;
import com.tianji.learning.service.ILearningLessonService;
import io.swagger.models.auth.In;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
@Slf4j
@RequiredArgsConstructor
public class LessonChangeListener {

    private final ILearningLessonService learningLessonService;

    private final LearningRecordMapper recordMapper;
    @Autowired
    private RedisCacheTemplate redisCacheTemplate;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "learning.lesson.pay.queue",durable = "true"),
            exchange = @Exchange(value = MqConstants.Exchange.ORDER_EXCHANGE,type = ExchangeTypes.TOPIC),
            key = MqConstants.Key.ORDER_PAY_KEY

    ))
    public void listenLessonPay(OrderBasicDTO orderBasicDTO){
        //1.健壮性处理（判断是否为空）
        if(orderBasicDTO == null || orderBasicDTO.getOrderId() == null || CollUtils.isEmpty(orderBasicDTO.getCourseIds()))
        {
            //数据有误，无需处理
            log.error("接收到MQ消息有误，订单数据为空");
            return;
        }
        //2.添加课程
        log.debug("监听到用户{}的订单{}，需要添加课程{}到课表中",orderBasicDTO.getUserId(),orderBasicDTO.getOrderId(),orderBasicDTO.getCourseIds());
        learningLessonService.addUserLessons(orderBasicDTO.getUserId(),orderBasicDTO.getCourseIds());
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "learning.lesson.refund.queue",durable = "true"),
            exchange = @Exchange(value = MqConstants.Exchange.ORDER_EXCHANGE,type = ExchangeTypes.TOPIC),
            key = MqConstants.Key.ORDER_REFUND_KEY
    ))
    public void listenLessonRefund(OrderBasicDTO orderBasicDTO){
        //1.健壮性处理（判断是否为空）
        if(orderBasicDTO == null || orderBasicDTO.getOrderId() == null || CollUtils.isEmpty(orderBasicDTO.getCourseIds()))
        {
            //数据有误，无需处理
            log.error("接收到MQ消息有误，订单数据为空");
            return;
        }
        log.debug("监听到用户{}的退款订单{}，需要从课表中删除课程{}",orderBasicDTO.getUserId(),orderBasicDTO.getOrderId(),orderBasicDTO.getCourseIds());
        learningLessonService.deleteUserLessons(orderBasicDTO.getUserId(),orderBasicDTO.getCourseIds());
    }


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "learning.record.delay.queue",durable = "true"),
            exchange = @Exchange(value = MqConstants.Exchange.REDIS_DELAY_EXCHANGE,type = ExchangeTypes.TOPIC),
            key = MqConstants.Key.REDIS_DELAY_KEY
    ))
    public void queryRedisRecord(LearningRecord record){

        log.debug("大key为：{}，hash_key为：{},moment：{}",record.getLessonId(),record.getSectionId(),record.getMoment());
        //查询redis
        LearningRecord redisRecord = redisCacheTemplate.redisCacheQueryRecord(record.getLessonId(),record.getSectionId());
        //如果有数据
        if(redisRecord!=null && redisRecord.getMoment().equals(record.getMoment())){
            // 一致，持久化播放进度数据到数据库
            // 更新学习记录的moment
            redisRecord.setFinished(null);
            recordMapper.updateById(redisRecord);
            // 4.2.更新课表最近学习信息
            LearningLesson lesson = new LearningLesson();
            lesson.setId(record.getLessonId());
            lesson.setLatestSectionId(record.getSectionId());
            lesson.setLatestLearnTime(LocalDateTime.now());
            learningLessonService.updateById(lesson);
        }
    }
}
